package com.example.statisticsservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.statisticsservice.client.OrdersClient;
import com.example.statisticsservice.entity.OrderStatistics;
import com.example.statisticsservice.mapper.OrderStatisticsMapper;
import com.example.statisticsservice.service.OrderStatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-08-11
 */
@Service
public class OrderStatisticsServiceImpl extends ServiceImpl<OrderStatisticsMapper, OrderStatistics> implements OrderStatisticsService {

    @Autowired
    private OrdersClient ordersClient;
    @Autowired
    private OrderStatisticsService statisticsService;
    @Override
    public void createData(String date) {
        LambdaQueryWrapper<OrderStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderStatistics::getDate,date);
        statisticsService.remove(queryWrapper);  // 同一天的数据可以多次生成，新数据覆盖旧数据
        BigDecimal payAmount = ordersClient.getTotalPayAmount(date);
        int totalNum = ordersClient.getTotalNum(date);
        OrderStatistics orderStatistics = new OrderStatistics();
        orderStatistics.setPayAmount(payAmount);
        orderStatistics.setPayNum(totalNum);
        orderStatistics.setDate(date);
        save(orderStatistics);
    }

    @Override
    public Map<String, Object> getShowData(String type, String begin, String end) {
        List<OrderStatistics> statistics = baseMapper.getData(type,begin,end);
        //创建3个List集合，一个日期List，一个数量List，一个金额List
        List<String> dateList = new ArrayList<>();
        List<Integer> payNumList = new ArrayList<>();
        List<BigDecimal> payAmountList = new ArrayList<>();
        for (int i = 0; i < statistics.size(); i++) {
            OrderStatistics orderStatistics = statistics.get(i);
            dateList.add(orderStatistics.getDate());
            if ("pay_num".equals(type)){
                payNumList.add(orderStatistics.getPayNum());
            }
            if ("pay_amount".equals(type)){
                payAmountList.add(orderStatistics.getPayAmount());
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("dateList",dateList);
        if ("pay_num".equals(type)){
            map.put("payNumList",payNumList);
        }else if ("pay_amount".equals(type)){
            map.put("payAmountList",payAmountList);
        }
        return map;
    }
}
